<?php

namespace app\admin\controller\fans;

use app\admin\controller\Base;
use app\admin\model\Authorizer;
use app\admin\model\Category;
use app\admin\model\FansCollect;
use app\wechat\controller\Openid;

/**
 * @author zero
 * @Time 2018/12/19
 *
 * Class Collect
 * @package app\admin\controller\fans
 *
 * 粉丝收集
 */
class Collect extends Base
{
    // 收集首页
    public function index()
    {
        return $this->fetch('fans/collect');
    }

    // 获取粉丝收集表数据
    public function get_list()
    {
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        $keyword = $this->request->post('keyword');
        $id_list = FansCollect::whereLike('name|ghid', '%' . $keyword . '%')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('id', 'desc')
            ->column('id');
        $data['total'] = FansCollect::whereLike('name|ghid', '%' . $keyword . '%')->count();

        $openid_redis = new Openid();
        $list = array();
        foreach ($id_list as $id) {
            $item = FansCollect::get($id);
            $item->collected = $openid_redis->get_fans_info_count($item->appid);
            $item->fans_num = $openid_redis->fans_num($item->appid, 'get');
            $item->save();
            array_push($list, $item);
        }

        if ($list) {
            $data['list'] = $list;
            return $data;
        } else {
            return false;
        }
    }

    // 添加账号界面
    public function add_acc_view()
    {
        return $this->fetch('fans/add_acc');
    }

    // 获取未添加的账号
    public function get_without_acc()
    {
        $page = $this->request->post('page');
        $keyword = $this->request->post('keyword');
        $category = $this->request->post('category', '');
        $category2 = $this->request->post('category2', '');
        if ($category !== '') {
            $map[] = ['category', '=', $category];
        }
        if ($category2 !== '') {
            $map[] = ['category2', '=', $category2];
        }
        $map[] = ['delstatus', '=', 1];
        // 获取已添加关注回复的账号
        $ghid_list = FansCollect::column('ghid');
        // 获取未绑定关注回复的账号
        $list = Authorizer::whereNotIn('ghid', $ghid_list)
            ->where($map)
            ->whereLike('name|ghid', '%' . $keyword . '%')
            ->limit(($page - 1) * 10, 10)
            ->select();
        $data['total'] = Authorizer::whereNotIn('ghid', $ghid_list)
            ->where($map)
            ->whereLike('name|ghid', '%' . $keyword . '%')
            ->count();

        if ($list) {
            foreach ($list as $v) {
                $v->category = Category::where('id', $v->category)->value('categoryname');
                $v->category2 = Category::where('id', $v->category2)->value('categoryname');
            }
            $data['list'] = $list;
            return $data;
        } else {
            return false;
        }
    }

    // 根据分类绑定公众号
    public function add_acc_by_category()
    {
        $ghid_list = $this->request->post('ghid_list');
        return $this->do_add_acc($ghid_list);
    }

    // 根据传入的原始id列表字符串绑定公众号
    public function add_acc_by_ghid()
    {
        // 获取并处理字符串
        $ghid_list = trim(trim($this->request->post('ghid_list')), ',');
        $ghid_list = explode(',', $ghid_list);
        return $this->do_add_acc($ghid_list);
    }

    // 添加绑定公众号逻辑
    public function do_add_acc($ghid_list)
    {
        $count = 0;
        // 遍历处理ghid
        foreach ($ghid_list as $ghid) {
            $ghid = trim(trim($ghid), ',');
            if ($gh = Authorizer::get(['ghid' => $ghid])) {
                if (!FansCollect::get(['ghid' => $ghid])) {
                    // 同时保证存在此账号,并且无绑定
                    $record = new FansCollect();
                    $record->name = $gh->name;
                    $record->ghid = $gh->ghid;
                    $record->appid = $gh->appid;
                    $record->refresh_token = $gh->refresh_token;
                    if ($record->save()) {
                        $count += 1;
                    }
                }
            }
        }
        // 返回添加成功的数量
        return $count;
    }

    //  删除绑定公众号逻辑
    public function del_acc()
    {
        $id = $this->request->post('id');

        $record = FansCollect::get($id);
        if ($record) {
            $openid_redis = new Openid();
            $openid_redis->del_fans_info($record->appid);
            return $record->delete();
        }
        return false;
    }

    // 批量删除公众号
    public function del_acc_list()
    {
        $id_list = $this->request->post('id_list');
        $count = 0;
        // 遍历处理任务
        foreach ($id_list as $id) {
            $record = FansCollect::get($id);
            if ($record) {
                $openid_redis = new Openid();
                $openid_redis->del_fans_info($record->appid);
                $openid_redis->fans_num($record->appid, 'rm');
                if ($record->delete()) {
                    $count++;
                }
            }
        }
        return $count;
    }

    // 收集全部公众号粉丝详细信息
    public function do_all_collect()
    {
        $id_list = $this->request->post('id_list');
        $openid_redis = new Openid();

        // 建立swoole连接
        $client = new \swoole_client(SWOOLE_SOCK_TCP);
        if (!$client->connect("127.0.0.1", 9508)) {
            die("connect failed.");
        }

        // 遍历处理任务
        foreach ($id_list as $id) {
            $collect = FansCollect::get($id);
            $collect->last_collect = date('Y-m-d H:i:s', time());
            $collect->save();

            $openid_redis->del_fans_info($collect->appid);

            // 拼接要发送的数据
            $data = array(
                'appid' => $collect->appid,
                'refresh_token' => $collect->refresh_token,
            );
            $msg = json_encode($data);

            // 发送数据
            $client->send($msg);
            usleep(10000);
        }

        $client->close();
        return true;
    }

    // 收集单个公众号粉丝详细信息
    public function do_collect()
    {
        $id = $this->request->param('id');

        // 拼接要发送的数据
        $collect = FansCollect::get($id);
        $collect->last_collect = date('Y-m-d H:i:s', time());
        $collect->save();

        $openid_redis = new Openid();
        $openid_redis->del_fans_info($collect->appid);

        $data = array(
            'appid' => $collect->appid,
            'refresh_token' => $collect->refresh_token,
        );
        $msg = json_encode($data);

        // 建立swoole连接
        $client = new \swoole_client(SWOOLE_SOCK_TCP);
        if (!$client->connect("127.0.0.1", 9508)) {
            die("connect failed.");
        }

        // 发送数据
        if ($client->send($msg)) {
            sleep(1);
            $client->close();
            return true;
        } else {
            return false;
        }
    }

}
